/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JTCPconnection;

import java.net.*;

/**
 *
 * @author M-R-D
 */
public class ConnectionListener implements Runnable
{
    private Thread t;
    private ServerSocket _server;
    private Socket _socketholder;
    private int _port;
    private TCPconnection _parent;

    public ConnectionListener(TCPconnection parent)
    {
        _parent = parent;
        init();
    }

    private void init()
    {
        t=new Thread(this);
        t.start();
    }

    @Override
	public void run()
    {
        try
        {
            _port = _parent.getPort();
            _server = new ServerSocket(_port);
            _socketholder = _server.accept();
            _parent.acceptConnection(_socketholder);
            _server.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            _parent.onConnectionLost();
        }
    }

    public void stop()
    {
        try
        {
            _server.close();
        }
        catch(Exception e)
        {}
        t.stop();
    }
}
